<template>
  <!-- 公司设置 -->
  <div class="setting-container">
    <div class="app-container">
      <el-card>
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first" class="tab-pane">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="changeShowFn"
            >新增角色</el-button>
            <!-- 弹框 -->
            <el-dialog :title="alterKey?'新增角色':'编辑角色'" :visible.sync="dialogShow">
              <el-form
                ref="addForm"
                label-width="80px"
                :model="addForm"
                :rules="addRules"
                :hide-required-asterisk="true"
              >
                <el-form-item label="角色名称" prop="name">
                  <el-input v-model="addForm.name" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                  <el-input v-model="addForm.description" placeholder="请输入角色描述" />
                </el-form-item>
              </el-form>
              <!-- 底部 -->
              <el-row slot="footer" type="flex" justify="center">
                <el-col :span="6">
                  <el-button
                    size="small"
                    @click="dialogShow = false"
                  >取消</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="roleSubmit"
                  >确定</el-button>
                </el-col>
              </el-row>
            </el-dialog>
            <el-table
              :data="tableData"
              border
              style="width: 100%;margin-top:10px"
            >
              <el-table-column type="index" label="序号" width="180" />
              <el-table-column
                prop="name"
                label="角色名"
                sortable
                width="180"
              />
              <el-table-column prop="description" sortable label="描述" />
              <el-table-column label="操作">
                <template v-slot="scoped">
                  <el-button type="success" @click="powerShowFn(scoped.row)">分配权限</el-button>
                  <el-button type="primary" @click="modifyFn(scoped.row)">修改</el-button>
                  <el-button type="danger" @click="removeRules(scoped.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second" class="tab-pane">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form
              label-width="120px"
              style="margin-top:50px"
              :model="companyInfo"
            >
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyInfo.name"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyInfo.companyAddress"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyInfo.mailbox"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyInfo.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width:400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 分配权限弹框 -->
    <el-dialog :title="`为【${roleName}】分配权限`" :visible.sync="powerShow">
      <el-tree
        ref="tree"
        :data="permissionTree"
        :default-checked-keys="defaultExpandedKeys"
        show-checkbox
        node-key="id"
        :props="defaultProps"
      />
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button
            size="small"
            @click="powerShow = false"
          >取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="changePermissionFn"
          >确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getAllRoles, getCompanyInfo, addNewRole, getRoledetailById, alterRoleById, removeRoleById, getAllpermissions, assignPremAPI } from '@/api/company'
import { mapGetters } from 'vuex'
import { changeTreeFn } from '@/utils/changeTree'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'first',
      companyInfo: {},
      tableData: [],
      dialogShow: false, // 新增/编辑弹框
      powerShow: false, // 分配权限弹框
      permissionTree: [], // 权限树行数据
      defaultExpandedKeys: [], // 树默认选中
      total: 0,
      page: 1, // 页码
      pagesize: 10, // 每页条数
      addForm: {
        name: '',
        description: '' // 角色描述
      },
      alterKey: true, // 判断调用改变还是添加接口
      roledetail: {},
      roleName: '',
      roleId: '',
      addRules: {
        name: [
          { required: true, message: '请输入新增角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入新增角色描述', trigger: 'blur' }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },

  computed: {
    ...mapGetters(['companyID'])
  },
  watch: {
    dialogShow(newVal) {
      if (!newVal) {
        this.$refs.addForm.resetFields()
        this.addForm.name = ''
        this.addForm.description = ''
      }
    },
    powerShow(newVal) {
      if (!newVal) {
        this.$refs.tree.setCheckedKeys([])
      }
    }
  },
  created() {
    this.getAllRolesFn()
    this.getInfo()
    this.getAllpermissionsFn()
  },
  methods: {
    // 获取公司信息
    async getInfo() {
      const res = await getCompanyInfo(this.companyID)
      this.companyInfo = res.data
    },
    // 获取所有角色
    async getAllRolesFn() {
      const res = await getAllRoles(this.page, this.pagesize)
      if (res.data.rows.length === 0 && this.page > 1) {
        this.page--
        this.getAllRolesFn()
      }
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 获取角色详情
    async getroleDetailFn(id) {
      const res = await getRoledetailById(id)
      return res
    },
    // 获取所有权限
    async getAllpermissionsFn() {
      const res = await getAllpermissions()
      this.permissionTree = changeTreeFn(res.data, '0')
    },
    // 新增角色/编辑 确认按钮
    roleSubmit() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        if (this.alterKey) {
          await addNewRole(this.addForm)
          this.$message.success('新增角色成功')
        } else {
          const data = { ...this.roledetail, ...this.addForm }
          await alterRoleById(data.id, data)
          this.$message.success('修改角色成功')
        }
        await this.getAllRolesFn()
        this.dialogShow = false
      })
    },
    // 新增角色按钮
    changeShowFn() {
      this.dialogShow = true
      this.alterKey = true
    },
    // 修改按钮
    async modifyFn(data) {
      const res = await this.getroleDetailFn(data.id)
      this.roledetail = res.data
      this.addForm.name = res.data.name
      this.addForm.description = res.data.description
      this.dialogShow = true
      this.alterKey = false
    },
    // 分页相关
    handleSizeChange(val) {
      this.pagesize = val
      this.page = 1
      this.getAllRolesFn()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getAllRolesFn()
    },
    // 删除按钮
    removeRules(id) {
      this.$confirm('确认删除角色么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await removeRoleById(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getAllRolesFn()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 权限管理弹窗
    async powerShowFn(data) {
      const res = await this.getroleDetailFn(data.id)
      this.defaultExpandedKeys = res.data.permIds
      this.roleName = data.name
      this.roleId = data.id
      /**
       * 当弹框没有渲染的时候,由于tree控件dom没有加载,setCheckedKeys是不存在的,会报错,
       * 所以我们需要使用this.$nextTick(callback)方法,该方法会在dom加载完毕之后,执行回调函数
       */
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.defaultExpandedKeys)
      })
      this.powerShow = true
    },
    async changePermissionFn() {
      const arr = this.$refs.tree.getCheckedKeys()
      await assignPremAPI(this.roleId, arr)
      this.$message.success('操作成功')
      this.powerShow = false
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  padding: 10px 30px;
}
.tab-pane {
  padding: 20px;
}
::v-deep .el-tabs__item {
  font-size: 18px;
  padding: 0 25px !important;
}
::v-deep .el-tabs__active-bar {
  width: 122px !important;
  left: -25px;
}
.el-pagination {
  text-align: center;
  margin-top: 20px;
}
</style>
